﻿using Gengens.Disk.Entity.entity.file;
using Gengens.Disk.Entity.model.file;
using Gengens.Disk.Repository.repository;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace Gengens.Disk.Service.service
{
    public class FilePathInfoService : BaseService<FilePathInfo>
    {
        private readonly DataInfoRepository _dataInfoRepository;
        public FilePathInfoService(FilePathInfoRepository repository,DataInfoRepository dataInfoRepository) : base(repository)
        {
            _dataInfoRepository = dataInfoRepository;
        }

        public override void Delete(FilePathInfo model)
        {
            //获取子目录
            List<FilePathInfo> children = GetChildren(model.Id);

            //删除级联资源
            List<DataInfo> waitDeletes = _dataInfoRepository.Select(d => children.Any(c => c.Id == d.FilePathId || c.Id == model.Id));
            _dataInfoRepository.DeleteRange(waitDeletes);

            //删除级联目录
            Models.RemoveRange(children);

        }

        //public void GetChildren(Guid basePathId,List<FilePathInfo> children) {
        //    var a1 = Models.Where(m => m.BasePathId == basePathId).ToList();
        //    children.AddRange(a1);
        //    foreach (var item in a1)
        //    {
        //        int count = Models.Count(m => m.BasePathId == item.Id);
        //        if (count > 0) {
        //            GetChildren(item.Id, children);
        //        }
        //    }
        //}

        public List<FilePathInfo> GetChildren(Guid basePathId)
        {
            var ret = Models.Where(m => m.BasePathId == basePathId).ToList();

            foreach (var item in ret) if (Models.Count(m => m.BasePathId == item.Id) > 0) 
                    ret.AddRange(GetChildren(item.Id));

            return ret;
        }
    }
}
